package com.redwine.app.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.redwine.app.APP;
import com.redwine.app.MessageAddressBookActivity;
import com.redwine.app.R;
import com.redwine.app.adapter.MessageAdapter;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.MessageListResponse;
import com.redwine.app.net.responses.SendMsgEvent;
import com.redwine.app.utils.Global;
import com.redwine.app.utils.NetUtil;
import com.redwine.app.view.EmptyView;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.redwine.app.utils.Utils.showToast;

/**
 * 消息主页
 * 作者：gassion on 17/8/26 14:54
 * 最可怕的敌人，就是没有坚强的信念。
 */
public class MessageFragment extends BaseFragment {

    @ViewInject(R.id.common_refresh_list_view)
    private PullToRefreshListView mListView;
    @ViewInject(R.id.header_title)
    private TextView headerTitle;
    @ViewInject(R.id.layout_right_tv_title)
    private TextView headerRightTitle;
    @ViewInject(R.id.empty_view)
    private EmptyView emptyView;
    private MessageAdapter messageAdapter;
    private View rootView;
    private ArrayList<MessageListResponse.DataEntity> responseData;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (null != rootView) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (null != parent) {
                parent.removeView(rootView);
            }
        } else {
            rootView = inflater.inflate(R.layout.activity_message, container, false);
            ViewUtils.inject(this, rootView);
            EventBus.getDefault().register(this);
            initView();
            requestFriendListData(true);
        }
        return rootView;
    }


    private void initView() {
        headerTitle.setText(getString(R.string.message));
        headerRightTitle.setVisibility(View.VISIBLE);
        headerRightTitle.setText(getString(R.string.message_address_book));
        headerRightTitle.setTextColor(getResources().getColor(R.color.white));
        mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                requestFriendListData(false);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

            }
        });
        mListView.setOnActionMoveListener(new PullToRefreshBase.OnActionMove() {
            @Override
            public void onMove(boolean isMove) {
                setUpdateTime(mListView);
            }
        });

        messageAdapter = new MessageAdapter(getActivity());
        mListView.setAdapter(messageAdapter);
        mListView.setEmptyView(emptyView);
        emptyView.bind();
    }


    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("MainScreen");

    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MainScreen");
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onStart() {
        super.onStart();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    /**
     * 请求朋友列表
     * 作者：gassion on 17/8/26 17:01
     * 最可怕的敌人，就是没有坚强的信念。
     */
    private void requestFriendListData(final boolean isLoading) {
        if (!NetUtil.checkNet(getActivity())) {
            if (messageAdapter.getData().isEmpty()) {
                setErrorView(emptyView, mListView);
            }
            showToast(R.string.generic_check);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (null != mListView)
                        mListView.onRefreshComplete();

                }
            }, 500);
            return;
        }

        if (isLoading)
            showWaiting();
        String url = NetworkConstants.FRIEND_LIST_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        GsonRequest<MessageListResponse> request = new GsonRequest<>(url, Request.Method.POST,
                MessageListResponse.class, false, params, new Response.Listener<MessageListResponse>() {
            @Override
            public void onResponse(MessageListResponse response) {
                if (isLoading)
                    dismissWaiting();
                if (null != mListView)
                    mListView.onRefreshComplete();
                if (response.isSuccess()) {
                    responseData = (ArrayList<MessageListResponse.DataEntity>) response.getData();
                    if (null != responseData && !responseData.isEmpty()) {
                        messageAdapter.setData(responseData);
                    } else {
                        messageAdapter.setData(null);
                        setEmptyView(emptyView, mListView);
                    }
                } else {
                    messageAdapter.setData(null);
                    setEmptyView(emptyView, mListView);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (isLoading)
                    dismissWaiting();
                if (null != mListView)
                    mListView.onRefreshComplete();
                setEmptyView(emptyView, mListView);
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }


    @OnClick({R.id.layout_right_tv_title})
    public void mClick(View v) {

        switch (v.getId()) {
            case R.id.layout_right_tv_title:
                Intent intent = new Intent(getActivity(), MessageAddressBookActivity.class);
                intent.putExtra(MessageAddressBookActivity.MESSAGE_LIST, responseData);
                getActivity().startActivity(intent);
                break;
        }
    }

    @Override
    protected void emptyOnclick() {
        emptyView.bind();
        mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        requestFriendListData(true);
    }

    public void onEventMainThread(SendMsgEvent event) {
        if (event.getSendType() == SendMsgEvent.REFURBISH_MESSAGE_DATA) {
            requestFriendListData(true);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

}